package org.abratuhi.kvngroupware.pubsub;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PubsubManager<T> implements SubscriptionStorage<T>{
	
	HashMap<String, Hub<T>> hubs = new HashMap<String, Hub<T>>();
	
	public PubsubManager(){
		
	}
	
	public PubsubManager(String[] attrIds, Value<T> reference){
		for(int i=0; i<attrIds.length; i++)
			hubs.put(attrIds[i], new Hub<T>(attrIds[i], 10, 100, 1, reference));
	}
	
	public List<Subscription<T>> intersection(List<Subscription<T>> l1, List<Subscription<T>> l2){
		ArrayList<Subscription<T>> result = new ArrayList<Subscription<T>>();
		for(int i=0; i<l1.size(); i++){
			if(l2.contains(l1.get(i))){
				result.add(l1.get(i));
			}
		}
		return result;
	}
	
	public String[] getAttributeIds(){
		return hubs.keySet().toArray(new String[hubs.keySet().size()]);
	}

	@Override
	public void addSubscription(Subscription<T> sub) {
		String[] attrIds = sub.getAttributeIds();
		for(int i=0; i<attrIds.length; i++)
			if(hubs.containsKey(attrIds[i]))
				hubs.get(attrIds[i]).addSubscription(sub);
	}

	@Override
	public List<Subscription<T>> findMatchingSubscriptions(Publication<T> pub) {
		String[] attrIds = pub.getAttributeIds();
		List<Subscription<T>> result = new ArrayList<Subscription<T>>();
		for(int i=0; i<attrIds.length; i++)
			if(hubs.containsKey(attrIds[i]))
				result = (i == 0) ? hubs.get(attrIds[i]).findMatchingSubscriptions(pub) : intersection(result, hubs.get(attrIds[i]).findMatchingSubscriptions(pub));
		return result;
	}

	@Override
	public List<Subscription<T>> findSubcriptions(String subscriberId) {
		String[] attrIds = getAttributeIds();
		List<Subscription<T>> result = new ArrayList<Subscription<T>>();
		for(int i=0; i<attrIds.length; i++)
			if(hubs.containsKey(attrIds[i]))
				result = (i == 0) ? hubs.get(attrIds[i]).findSubcriptions(subscriberId) : intersection(result, hubs.get(attrIds[i]).findSubcriptions(subscriberId));
		return result;
	}

	@Override
	public void removeSubscription(Subscription<T> sub) {
		String[] attrIds = getAttributeIds();
		for(int i=0; i<attrIds.length; i++)
			hubs.get(attrIds[i]).removeSubscription(sub);
	}

	@Override
	public void removeSubscriptions(String subscriberId) {
		String[] attrIds = getAttributeIds();
		for(int i=0; i<attrIds.length; i++)
			hubs.get(attrIds[i]).removeSubscriptions(subscriberId);
	}

	@Override
	public void updateSubscription(Subscription<T> sub) {
		String[] attrIds = getAttributeIds();
		for(int i=0; i<attrIds.length; i++)
			hubs.get(attrIds[i]).updateSubscription(sub);
	}

}
